#include "fanfou.h"
#include "ui_fanfou.h"




Fanfou::Fanfou(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Fanfou)
{
    ui->setupUi(this);
    //ui->tbTimeline->setFrameStyle(true);
    //ui->tbTimeline->setFrameStyle(QFrame::Plain);
    ui->tbTimeline->setAcceptRichText(false);
    login();
    fetchTimeline();

}

void Fanfou::login()
{
    //read login info from file
    QFile file("login.txt");
    if(file.open(QIODevice::ReadOnly))
    {
        //QTextStream stream(&file);
        usernamePassword = file.readLine(0);
        usernamePassword.remove(usernamePassword.length()-1,1);
        //QMessageBox::information(this,"Debut",usernamePassword);

    }
    else
    {
        QMessageBox::information(this,"Login Error", "Unable to read login info, please check your login file. \n(Please Create a login.txt file and fill username:passwd in the file)");
    }

    urlUpdate="http://api.fanfou.com/statuses/update.xml";
    urlTimeline="http://api.fanfou.com/statuses/friends_timeline.xml";
    authString = QByteArray("Basic ").append(usernamePassword.toBase64());
}

Fanfou::~Fanfou()
{
    delete ui;
}

void Fanfou::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}



void Fanfou::on_btnQuit_clicked()
{
    this->close();
}

void Fanfou::on_btnSubmit_clicked()
{
    fetchTimeline();
    QNetworkAccessManager *nam = new QNetworkAccessManager(this);   //define nam

    QUrl param;
    QByteArray data;
    param.addQueryItem("status", (ui->teMessage->toPlainText()).toUtf8());
    data.append(param.toString());
    data.remove(0,1);


    //set request header
    QNetworkRequest request;
    request.setUrl(QUrl(urlUpdate));
    request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setRawHeader("Accept", "text/xml");
    request.setRawHeader("Authorization",authString);

    nam->post(request,data);
    ui->teMessage->clear();
    connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(sendMessage(QNetworkReply*)));
}


void Fanfou::sendMessage(QNetworkReply* reply)
{
    //TODO: deal with http reply
    QVariant statuCode =
            reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(statuCode.toInt() == 200)
    {
        QMessageBox::information(this,"Sender","Message sent");
    }
    else
    {
        QMessageBox::information(this, "Sender", "Send failed : "+statuCode.toString());
    }
    delete reply;

}


void Fanfou::fetchTimeline()
{
    //TODO:
    //read time line and put it on the
    QNetworkAccessManager *nam = new QNetworkAccessManager(this);   //define nam
  //setting password and url
    QUrl url("http://api.fanfou.com/statuses/friends_timeline.xml?count=10");  //xml or json or rss



    //set request header
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setRawHeader("Accept", "text/xml");
    request.setRawHeader("Authorization",authString);

    nam->get(request);
    connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(fetchFinished(QNetworkReply*)));

}


QList< QMap<QString, QString> > Fanfou::analyseXML(QByteArray source)
{
    //This function is used to save XML info to a List.
    QList< QMap<QString, QString> > statuses;
    QDomDocument doc;
    //Change encode fomart
    QString strSource = QString::fromUtf8(source);
    //QMessageBox::information(this,"debug",strSource);
    doc.setContent(source);
    QDomElement root = doc.documentElement();
    if(root.tagName() != "statuses")
    {
        QMessageBox::warning(this, "Error", "XML Error while reading root elment");
        exit(0);
    }
    QDomNode node = root.firstChild();
    while(!node.isNull())
    {
        //read status
        QMap<QString, QString> status;
        //get user info
        //If you need more infor form XML, just come and modify here!!!!!
        //----------------attention!!!!-----------------------

        QDomNode statusNode = node.firstChild();
        while(!statusNode.isNull())
        {
            QDomElement statusElm = statusNode.toElement();
            //read infos except user
            while(statusElm.tagName() != "user")
            {
                status[statusElm.tagName()] = statusElm.text();
                statusElm = statusElm.nextSiblingElement();

            }

            //read info from user
            QDomNode userNode = statusNode.firstChild();
            while(!userNode.isNull())
            {
                QDomElement userElem = userNode.toElement();
                status[userElem.tagName()] = userElem.text();
                userNode = userNode.nextSibling();
            }
            /*
            if(statusElm.tagName() == "created_at")
                status["created_at"] = statusElm.text();
            else if(statusElm.tagName() == "text")
                status["text"] = statusElm.text();
            */
            statusNode = statusNode.nextSibling();

        }
        /*status["created_at"] = statusElem.attribute("created_at");
        QMessageBox::information(this, "debug", statusElem.attribute("text"));
        status["text"] = statusElem.attribute("text");
        status["userName"] = statusElem.attributeNode("user").toElement().attribute("name");
        status["userID"] = statusElem.attributeNode("user").toElement().attribute("user");
        status["picURL"] = statusElem.attributeNode("user").toElement().attribute("profile_image_url");
        */
        node = node.nextSibling();
        statuses.push_back(status);

    }

    return statuses;


}



void Fanfou::fetchFinished(QNetworkReply* reply)
{
    QVariant statusCodeV =
            reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if(statusCodeV.toInt() == 200)
    {

        QByteArray bytes = reply->readAll();
        QList< QMap<QString, QString> > timeLineList = analyseXML(bytes);
        QString rawTimeLine = QString::fromUtf8(bytes);
        //Put everything you need to timeLine;
        ui->tbTimeline->setText("<html>");
        for(int i=0; i < timeLineList.count(); i++)
        {
            //ui->tbTimeline->setStyleSheet("font-size:16px");            
            //ui->tbTimeline->append("<IMG SRC=\""+timeLineList.at(i)["profile_image_url"]+"\" >");
            ui->tbTimeline->append(
                    "<div style=\"font:italic; color:blue;\">"
                    +timeLineList.at(i)["name"]+
                    "</div>"+": "
                    +timeLineList.at(i)["text"]
                    );
            //ui->tbTimeline->append(timeLineList.at(i)["text"]);
            //ui->tbTimeline->setStyleSheet("font-size:8px");
            ui->tbTimeline->append("<div style=\"font-size:8px\">"
                                   +timeLineList.at(i)["created_at"]
                                   +"</div>");
            ui->tbTimeline->append("---------------------------------------------------------------");
            //ui->tbTimeline->append(QString::number((double)i));
            //ui->tbTimeline->append("<hr></hr>");

        }
        //ui->tbTimeline->append("</html>");

    }
    else
    {
        QMessageBox::information(this, "Error", "Unable to fetch Time Line, Check your login info in login.txt.");
    }


}



void Fanfou::on_btnRefresh_clicked()
{
    fetchTimeline();
}
